#include <iostream>
#include <string>
#include <memory>
#include "EpollServer.hpp"
#include "Protocol.hpp"
using namespace pr;

std::string Echo(std::string requst)
{
    requst += "[echo]\r\n";

    return requst;
}
Response CalculatorHelper(const Request& request)
{
    Response tmp;
    switch (request._op)
    {
    case '+':
        tmp._result = request._x + request._y;
        break;
    case '-':
        tmp._result = request._x - request._y;
        break;
    case '*':
        tmp._result = request._x * request._y;
        break;
    case '/':
        if (request._y == 0)
            tmp._code = 1;
        else
            tmp._result = request._x / request._y;
        break;
    case '%':
        if (request._y == 0)
            tmp._code = 2;
        else
            tmp._result = request._x % request._y;
        break;
    default:
        tmp._code = 3;
        break;
    }
    return tmp;
}

void Calculator(Connection* con, Request& request)
{
    Response res = CalculatorHelper(request);
    std::string sendstr;
    res.Serialize(&sendstr);
    sendstr = pr::AddHeader(sendstr);
    //向文件描述符发送数据-->需要知道文件描述符是哪个
    //该怎么发送呢？？
    //epoll中，关于fd的读取，一般要设置(一直要让epoll关心的)
    //关于fd的写入，一般是按需设置(不能常设置)，只有有需要的时候，才设置！！

    //Debug--version1版本
    con->outbuffer_ += sendstr;
    //需要对write事件进行关心--》开启对写事件进行关心
    con->R->EnbleWriteRead(con,true,true);   //让内核对写事件进行关心
}
void Usage(std::string u)
{
    std::cout << "Usage:\n\t" << u << "serverport" << std::endl;
}
int main(int argv, char *argc[])
{
    if (argv != 2)
    {
        Usage(argc[0]);
        exit(USAGE_ERROR);
    }
    uint16_t port = atoi(argc[1]);

    std::unique_ptr<EpollServer> uqsv(new EpollServer(Calculator));
    uqsv->InitServer();
    uqsv->Dispatcher();
    return 0;
}